<template>
  <view class="padding-sm">
    <uni-forms-item label="用户昵称" label-width="80px">
      <uni-easyinput type="nickname" v-model="userInfo.nickname" @blur="onBlur" placeholder="请输入用户昵称" />
    </uni-forms-item>
    <view class="padding">
      <button class="cu-btn block bg-cyan margin-tb-sm lg" type="" @click="editNickname">修改昵称</button>
    </view>
  </view>
</template>

<script>
  import {
    mapMutations,
    mapState
  } from 'vuex'
  export default {
    onLoad() {
      this.userInfo.nickname = this.userInfo.nickname ? this.userInfo.nickname : "";
    },
    computed: {
      // 2. 从 m_user 模块中导入需要的 token 字符串
      ...mapState('m_user', ['userInfo']),
    },
    data() {
      return {

      }
    },
    methods: {
      ...mapMutations('m_user', ['updateUserNickname']),
      // 修改昵称
      async editNickname() {
        if (!this.userInfo.nickname) {
          uni.$showMsg('请重新输入昵称内容');
        }
        if (this.userInfo.nickname > 11) {
          uni.$showMsg('昵称长度最大为11');
        }
        const {
          data: res
        } = await uni.$http.post('/user/update/nickname', this.userInfo.nickname)
        if (res.code !== 200) return uni.$showMsg()
        // 上传成功
        uni.showToast({
          title: '修改成功',
        });
        this.updateUserNickname(this.userInfo.nickname);
      },
      // 触发blur
      onBlur(e) {
        this.userInfo.nickname = e.detail.value;
      }
    }
  }
</script>

<style>

</style>